package com.bbs.toutiao.utils;


import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.RandomUtil;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 描述: 验证码
 * 作者： zhangBin
 * 时间： 2023/9/18 18:35
 * 版本： 1.0
 */

@Slf4j
@Component
public class MsgCodeUtil {


    public static final TimedCache<String, String> timedCache = CacheUtil.newTimedCache( 120 * 1000);

    public static String getCode(String email) {
        //启动定时任务，每5毫秒清理一次过期条目，注释此行首次启动仍会清理过期条目
        String captcha = RandomUtil.randomNumbers(6);//生成6位验证码
        timedCache.put(email, captcha);
        return captcha;
    }

    public static void startCleanerCache() {
        timedCache.schedulePrune(5);
    }

    public static Boolean booleanCode(String email, String captcha) {

        String code = null;
        try {
            code = timedCache.get(email,false);
            log.info("用户获取了验证码：" + code + "申请的账号为：" + email + "验证码为：" + captcha);
        } catch (NullPointerException e) {
            throw new BaseException(ExceptionEnum.NOT_FOUND_CODE);
        }
        if (Objects.equals(captcha, "")) {
            throw new BaseException(ExceptionEnum.NOT_CODE);  //捕获验证码为空
        }
        return captcha.equals(code);
    }

}
